package it.sd.pwframework.admin.bean;

import it.sd.pwframework.business.service.CommonService;
import it.sd.pwframework.business.service.PwServiceService;
import it.sd.pwframework.persistence.model.spider.PWParam;
import it.sd.pwframework.persistence.model.spider.PWService;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.persistence.Transient;

@ManagedBean(name="pwserviceBean")
@ViewScoped
public class PWServiceBean extends AbstractJsfBean {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@ManagedProperty(value="#{commonService}")
	@Transient
    private transient CommonService commonService;

	public CommonService getCommonService() {
		return commonService;
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	@ManagedProperty(value="#{pwserviceService}")
	@Transient
    private transient PwServiceService pwserviceService;

	public PwServiceService getPwserviceService() {
		return pwserviceService;
	}

	public void setPwserviceService(PwServiceService pwserviceService) {
		this.pwserviceService = pwserviceService;
	}

	private PWService service = new PWService();

	public PWService getService() {
		return service;
	}

	public void setService(PWService service) {
		this.service = service;
	}

	
	public void init() {
		try {
			setId(null);
		} catch(Exception e ){
			log.error("error loading entities", e);
		}
	}
	
	public synchronized void setId(Long id) {
		try {
			
			if (id!=null) {
				service = pwserviceService.getService(id);
			}
			
		} catch(Exception e) {
			log.error("error retrieving row: " + id, e);
		}
	}

	public Long getId() {
		return service.getId();
	}

	private boolean insertMode;
	
	public boolean getInsertMode() {
		return insertMode;
	}
	
	public void doSave() {
		try {
				pwserviceService.save(service);
				showInfoMessage("Salvataggio completato");
				addCallBackOk();
				
		} catch (Exception e) {
			showErrorMessage("Errore durante salvataggio", e);
		}
	}

	private PWParam param;
	
	public PWParam getParam() {
		return param;
	}

	public void setParam(PWParam param) {
		this.param = param;
	}

	public void doNewServiceInputParam() {
		
		int progressivo = 1;
		for (PWParam param  : service.getInputParams()) {
			if (param.getProgressivo()>=progressivo) {
				progressivo = param.getProgressivo() +1;
			}
		}			
		
		PWParam param = new PWParam();
		param.setName("name-" + progressivo);
		param.setProgressivo(progressivo);
		param.setValue("value-" + progressivo);
		
		service.getInputParams().add(param);
	}
	
	
	
}
